package gp;

/**
 * @author Beacom
 * @version 1.0
 * @created 18-Feb-2008 12:43:42 PM
 */
public class OperandNode extends OrganismNode {

	private double value;
	/**
	 * if this contains a value other than null the OperandNode represents a variable
	 * with the name specified by variable
	 */
	private String variable;

	public OperandNode() {
     value = 0.0;
     variable = null;
	}
	
	public OperandNode(OperandNode original) {
		this.value = original.value;
		this.variable = original.variable;
	}
	
	public OperandNode createCopy() {
		return new OperandNode(this);
	}
	
	public OperandNode(String var) {
	  variable = var;   // setting up var	
	}
	
	public OperandNode (double val) {
		value = val;
	}
	
	public OperandNode mutate() {
			this.selectRandomOperandValue(new String[]{"x"});
		return this;
	}
	
	public OperandNode selectRandomOperandValue(String[] variables) {
		double randomNumber = Math.random();
		
		if(randomNumber < 0.75 || variables == null) {
			// assign a value
			value = Math.random() * 10.0; //  0 <= value < 10
			value += 0.001;
			//System.out.println("value of " + value + " assigned");
		} else {
			// assign a variable
			if(variables.length == 0) {
				variable = variables[0];
			} else {
				double increment = (1 / variables.length);
				randomNumber = Math.random();
				for(int i = 0; i < variables.length; i++) {
					if(randomNumber < increment) {
						variable = variables[i];
						break;
					}
					increment += increment;
				}
			}
		}
		
		return this;
	}

	public void finalize() throws Throwable {
		super.finalize();
	}

	public double evaluate() {
		return value;
	}

	public void setVar(String var) {
		variable=var;
	}
	
	public void setVal(double val) {
		value=val;
	}
	
	public double getVal() {
	 return value;
	}
	
	public String getVar() {
		return variable;
	}
	
	public void setVariable(String var, double val) {
		if (var.equals(variable))
			value = val;
	}
	
	public String toString() {
		if (variable==null)
			return String.format("%.2f",value);
		else
			return variable;
	}
	/*public String toString() {
		String output = " OperandNode ";
		if(variable == null) {
			output += Double.toString(value);
		} else {
			output += variable;
		}
		return output;
	}*/
}